<template>
  <div class="settlement-report-list table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable ref="filterTable" :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <!-- <a-range-picker v-model="requestReportTime" style="width: 240px" size="medium" value-format="YYYY-MM-DD HH:mm:ss" :time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }" :allow-clear="false" shortcuts-position="left" :shortcuts="rangeShortcuts()" />
            <a-button v-show="isOneSellerSellected" class="gray-outline" size="medium" @click="onRequestReportFromAmz">申请报告</a-button>

            <a-button class="gray-outline" v-if="isAdmin" size="medium">请求所有店铺近3个月报告，非管理员请不要操作</a-button>
            <a-button class="gray-outline" v-if="isAdmin" size="medium">重新解析近一个月报告</a-button> -->
            <div class="flex-c">
              <a-select v-model="updateMarketId" allow-search allow-clear style="width: 120px" placeholder="选择站点">
                <a-option v-for="(item, index) in markedtList" :key="index" :value="item.marketplaceId">{{ item.marketplaceName }}</a-option>
              </a-select>
              <a-button class="gray-outline" v-if="isAdmin" size="medium" @click="onUpdateMarketPlace">设置市场</a-button>
            </div>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="settlement_id"
            :loading="tableLoading"
            :data="tableList"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :summary="true"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :bordered="{ headerCell: true }"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="市场" :width="50" fixed="left">
                <template #cell="{ record }">
                  <p :class="{ warningColor: !$extract(marketPlaceList[record.marketplace_id], 'code') }">
                    {{ $extract(marketPlaceList[record.marketplace_id], 'code') || record.marketplace_id }}
                  </p>
                </template>
              </a-table-column>
              <a-table-column title="店名" :width="160" fixed="left">
                <template #cell="{ record }">
                  <template v-if="record.shop_name">
                    <TextLimit :rows="2" :val="record.shop_name" />
                  </template>
                  <div v-else>
                    <TextLimit class="warningColor" :rows="1" :val="oneShopName(record)" />
                    <p style="font-size: 10px; color: rgb(197, 196, 196)">如果市场确认无误，可忽略</p>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="结算ID" :width="100" fixed="left">
                <template #cell="{ record }">
                  <p class="highlight cursor" @click="openDetail(record)">{{ record.settlement_id }}</p>
                </template>
              </a-table-column>
              <a-table-column title="打款时间(0时区)" data-index="deposit_date" :width="180" :sortable="sortable" />
              <a-table-column title="开始时间(0时区)" data-index="settlement_start_date" :width="180" :sortable="sortable" />
              <a-table-column title="结束时间(0时区)" data-index="settlement_end_date" :width="180" :sortable="sortable" />
              <a-table-column title="货币" data-index="currency" :width="70" :sortable="sortable" />
              <a-table-column title="结算金额" data-index="total_amount" :width="100" :sortable="sortable" align="right" />
              <a-table-column title="结算金额(CNY)" data-index="cny_amount" :width="130" :sortable="sortable" align="right" />
              <a-table-column title="结算金额(USD)" data-index="usd_amount" :width="130" :sortable="sortable" align="right" />
              <a-table-column title="未分配" data-index="no_alloc_amount" :bodyCellStyle="{ backgroundColor: '#ddd' }" :width="120" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <p v-if="record.status === 1" style="color: green"> {{ record.no_alloc_amount }} </p>
                  <p v-else> {{ record.no_alloc_amount }}</p>
                </template>
              </a-table-column>
              <a-table-column title="状态" data-index="status" :width="70" :sortable="sortable" align="right">
                <template #cell="{ record }">
                  <p v-if="record.status === 1"> 已完成</p>
                  <a-button v-else size="mini" class="gray-outline" @click="onConfirmFinish(record)">完成</a-button>
                </template>
              </a-table-column>
              <a-table-column v-if="isAdmin" title="分配一(绑定)" data-index="total_salesman_amount" :width="120" align="right" :sortable="sortable" />
              <a-table-column v-if="isAdmin" title="分配二(分配)" data-index="amount_alloced" :width="120" align="right" :sortable="sortable" />
              <a-table-column v-if="isAdmin" title="分配三(广告)" data-index="total_ad_amount" :width="120" align="right" :sortable="sortable" />
              <a-table-column title="明细数量" data-index="item_total_rows" :width="90" align="right" :sortable="sortable" />
              <a-table-column title="明细核对" :width="100" align="right">
                <template #cell="{ record }">
                  <span v-if="record.total_amount === record.item_total_amount" style="color: green">√</span>
                  <span v-else style="color: red">× {{ record.item_total_amount }}</span>
                </template>
              </a-table-column>
              <a-table-column title="CNY汇率" data-index="cny_rate" :width="80" align="right" />
              <a-table-column title="USD汇率" data-index="usd_rate" :width="80" align="right" />
              <a-table-column title="店长" data-index="manager_user_name" :width="80" align="center" />
              <a-table-column title="操作" :width="80" align="center">
                <template #cell="{ record }">
                  <a-button type="text" size="mini" :disabled="downloadLoading" @click="downloadReportId(record)">下载报告</a-button>
                </template>
              </a-table-column>
            </template>
            <template #summary-cell="{ column, record }">
              <p v-if="column.dataIndex == 'sort'">合计</p>
              <p v-else-if="column.dataIndex == 'total_amount'">{{ record.total_amount.toFixed(2) }}</p>
              <p v-else-if="column.dataIndex == 'cny_amount'">CNY {{ record.cny_amount.toFixed(2) }}</p>
              <p v-else-if="column.dataIndex == 'usd_amount'">USD {{ record.usd_amount.toFixed(2) }}</p>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.currentPage" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <a-modal v-model:visible="openDownLoadTitle" width="400px" :footer="false" title="提示" title-align="start" :mask-closable="false">
    <div style="text-align: center">
      <p class="text-c" style="font-size: 16px">您的导出任务已发起，稍后前往下载中心下载</p>
      <a-button style="margin-top: 20px" type="primary" status="success" @click="toDownLoad">前往下载中心</a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, ref, computed, reactive, PropType, watch } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import { settlementReportFind, saveSettlementStatus, ListSettlementItem, saveSettlementMarketplace } from '@/api/finance/summaryReport'
  import dayjs from 'dayjs'
  import { marketPlaceList } from '@/utils/globalData'
  import useUserStore from '@/store/modules/user'
  import { commonExport } from '@/api/export'
  import { useRouter } from 'vue-router'
  import { getStartAndEndTime } from '@/utils/timeFormat'

  onMounted(() => {
    setDefaultSearch()
  })
  const emit = defineEmits(['openDetail', 'toSearch'])
  const props = defineProps({
    searchVal: {
      type: Object,
      default: () => {},
    },
    markedtList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  const searchVal = ref<any>({
    pageSize: 20,
    currentPage: 1,
  })
  const filterData = ref<any>({})
  const router = useRouter()
  const openDownLoadTitle = ref(false)
  const tableLoading = ref(false)
  const downloadLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const tableListMap = ref({})
  const reportchain = ref<any>({})
  const selectIds = ref([])
  const userStore = useUserStore()
  const tableRef = ref()
  const total = ref(0)
  const updateMarketId = ref()
  const seachData = ref<any>({})
  const filterTable = ref()
  const fundTransferStatusMap = {
    Succeeded: { value: 'Succeeded', label: '成功' },
    Failed: { value: 'Failed', label: '失败' },
    Unknown: { value: 'Unknown', label: '未知' },
    Processing: { value: 'Processing', label: '处理中' },
  }
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
  }) as any
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplace_id_list',
      label: '站点',
      value: ref(props.searchVal.marketplace_id_list ? props.searchVal.marketplace_id_list?.split(',') : null),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'seller_id_list',
      label: '全部店铺',
      value: ref(props.searchVal?.seller_id_list ? props.searchVal.seller_id_list.split(',') : null),
      type: 'select_multiple',
      width: 160,
      optionItems: [],
    },
    {
      type: 'input_search',
      key: 'settlement_id',
      value: ref(),
      label: '结算ID',
      width: 160,
      isMultiple: false,
    },
    {
      key: 'fundTransferStatus',
      label: '回款状态',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: Object.values(fundTransferStatusMap),
    },
    {
      key: 'status',
      label: '状态',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        { value: '1', label: '已完成' },
        { value: '-1', label: '未完成' },
      ],
    },
    {
      key: 'no_marketplaceid',
      label: '未绑定市场',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        { value: '1', label: '是' },
        { value: '2', label: '否' },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'settlementEnd',
      keyItems: [
        { label: '结算开始时间', value: 'settlementStart' },
        { label: '结算结束时间', value: 'settlementEnd' },
        { label: '转账时间', value: 'deposit' },
      ],
      keyWidth: '130',
      value: ref(getStartAndEndTime('this_month', 'YYYY-MM-DD HH:mm:ss')),
      placeholder: '请输入',
      label: '结算结束时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const isOneSellerSellected = computed(() => seachData.value.marketplace_id_list?.length === 1 && seachData.value.seller_id_list?.length === 1)
  const isAdmin = computed(() => userStore.admin)

  // 初始化查询
  function setDefaultSearch() {
    filterData.value = {
      marketplace_id_list: props.searchVal.marketplace_id_list,
      seller_id_list: props.searchVal.seller_id_list,
      dataType: 'settlementEnd',
      startDate: getStartAndEndTime('this_month', 'YYYY-MM-DD HH:mm:ss')?.[0],
      endDate: getStartAndEndTime('this_month', 'YYYY-MM-DD HH:mm:ss')?.[1],
    }
    getTableList()
  }
  // 显示店铺
  function oneShopName(row: any) {
    return props.shopList.find((item: any) => item.sellerId === row.seller_id)?.shopName || '未知'
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.currentPage = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.currentPage = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 设置查询条件
  function setSearchval() {
    let _params: any = JSON.parse(JSON.stringify(filterData.value))
    _params.marketplace_id_list = _params.marketplace_id_list ? _params.marketplace_id_list?.split(',') : []
    _params.seller_id_list = _params.seller_id_list ? _params.seller_id_list?.split(',') : []

    // 非管理员未选择店铺时默认传所有店铺
    if (!isAdmin.value && _params.seller_id_list?.length === 0) {
      _params.seller_id_list = props.shopList?.map((item: any) => item.sellerId) || []
      if (!_params.seller_id_list?.length) {
        Message.error('请选择店铺')
        return
      }
    }
    _params.no_marketplaceid = _params.no_marketplaceid === '1' ? true : undefined

    if (_params.status === '1') {
      _params.status_done = true
    } else if (_params.status === '-1') {
      _params.status_process = true
    }
    if (_params.startDate && _params.endDate) {
      _params[`${_params.dataType}DateStart`] = dayjs(_params.startDate).unix()
      _params[`${_params.dataType}DateEnd`] = dayjs(_params.endDate).unix()
    }
    delete _params.startDate
    delete _params.endDate
    delete _params.dataType

    _params.sortKey = searchVal.value.sortKey
    _params.sortOrder = searchVal.value.sortOrder
    return _params
  }
  // 获取商品列表
  async function getTableList() {
    tableLoading.value = true
    tableList.value = []
    reportchain.value = {}
    const _param = {
      needCount: true,
      pageSize: searchVal.value.pageSize,
      currentPage: searchVal.value.currentPage,
      param: setSearchval(),
    }
    tableRef.value.selectAll(false)
    const res: any = await settlementReportFind(_param)
    seachData.value = _param.param
    emit('toSearch', filterData.value)
    tableLoading.value = false
    let list = res?.data?.rs?.result || []
    total.value = res?.data?.rs?.rows || 0
    tableListMap.value = {}
    list.forEach((item: any) => {
      item.no_alloc_amount = ((item?.total_amount || 0) - (item?.total_salesman_amount || 0) - (item?.amount_alloced || 0) - (item?.total_ad_amount || 0)).toFixed(2)
      tableListMap.value[item.settlement_id] = item
    })
    tableList.value = list
    if (isOneSellerSellected.value) {
      reportchain.value = {
        list: res?.data?.rs?.result || [],
      }
    }
  }

  // 打开明细报告
  function openDetail(row: any) {
    emit('openDetail', row.settlement_id)
  }
  // 完成结算
  async function onConfirmFinish(row: any) {
    Modal.error({
      title: '确认',
      content: '请再次确认是否完成该结算报告',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        let param = {
          list: [
            {
              seller_id: row.seller_id,
              settlement_id: row.settlement_id,
              settlement_start_date: row.settlement_start_date,
              settlement_end_date: row.settlement_end_date,
              status: 1,
            },
          ],
        }
        const res: any = await saveSettlementStatus({ param: param })
        if (res) {
          Message.success('删除成功')
          row.status = 1
        }
      },
    })
  }
  // // 排序
  // function sorterChange(dataIndex: string, direction: string) {
  //   searchVal.value.sortKey = null
  //   searchVal.value.sortOrder = null
  //   if (direction) {
  //     searchVal.value.sortKey = dataIndex
  //     searchVal.value.sortOrder = direction === 'ascending' ? 'asc' : 'desc'
  //   }
  //   searchVal.value.currentPage = 1
  //   getTableList()
  // }
  // 设置市场
  async function onUpdateMarketPlace() {
    if (!updateMarketId.value) {
      Message.error('请选择市场')
      return
    }
    if (!selectIds.value.length) {
      Message.error('请选择报告')
      return
    }
    let items = selectIds.value.map((id: string) => {
      let _data = tableListMap.value[id]
      return {
        settlement_id: _data.settlement_id,
        seller_id: _data.seller_id,
        settlement_end_date: _data.settlement_end_date,
        settlement_start_date: _data.settlement_start_date,
        marketId: updateMarketId.value,
      }
    })
    const res: any = await saveSettlementMarketplace({ param: { list: items } })
    if (res) {
      Message.success('设置成功')
      getTableList()
    }
  }
  // 下载报告
  async function downloadReportId(row: any) {
    downloadLoading.value = true
    const res: any = await ListSettlementItem({
      param: {
        settlement_id: row.settlement_id,
        seller_id: row.seller_id,
        settlement_start_date: row.settlement_start_date,
        settlement_end_date: row.settlement_end_date,
      },
    })
    let list = res?.data?.rs?.result || []
    if (!list.length) {
      Message.error('未获取到报告明细，请联系管理员~')
      return
    }
    // 下载表头
    let columnList = [
      { name: '序号', key: 'item_index', keyType: '1' },
      { name: '店铺', key: 'shop_name', keyType: '1' },
      { name: '结算ID', key: 'settlement_id', keyType: '1' },
      { name: '金额', key: 'amount', keyType: '1' },
      { name: '币种', key: 'currency', keyType: '1' },
      { name: '开始时间', key: 'settlement_start_date', keyType: '1' },
      { name: '结束时间', key: 'settlement_end_date', keyType: '1' },
      { name: '发布时间', key: 'posted_Date_Time', keyType: '1' },
      { name: '运营', key: 'salesman_name', keyType: '1' },
      { name: '订单号', key: 'order_Id', keyType: '1' },
      { name: '订单itemCode', key: 'order_Item_Code', keyType: '1' },
      { name: '履约方式', key: 'fulfillment_Id', keyType: '1' },
      { name: 'SellerSku', key: 'sku', keyType: '1' },
      { name: '产品SKU', key: 'product_sku', keyType: '1' },
      { name: 'ASIN', key: 'asin', keyType: '1' },
      { name: '交易类型', key: 'transaction_type', keyType: '1' },
      { name: '金额类型', key: 'amount_Type', keyType: '1' },
      { name: '金额说明', key: 'amount_Description', keyType: '1' },
      { name: '商品数量', key: 'quantity_purchased', keyType: '1' },
      { name: '汇总类型', key: 'sum_type_name', keyType: '1' },
    ]
    let dataList = list.map((item: any) => {
      let items = columnList.map((el: any) => {
        return {
          key: el.key,
          value: item[el.key] || '',
        }
      })
      return items
    })
    const _result = await commonExport({
      fileName: `结算报告-${row.shop_name}-${row.settlement_id}.xlsx`,
      sheetName: 'sheet',
      fromLocation: '结算报告',
      dataList,
      columnList,
    })
    if (_result) {
      openDownLoadTitle.value = true
      downloadLoading.value = false
    }
  }
  // 前往下载中心；
  function toDownLoad() {
    openDownLoadTitle.value = false
    router.push('/system/download/download')
  }
  watch(
    () => props.shopList,
    (newVal) => {
      let optionItems = newVal.map((el: any) => {
        return {
          label: el.shopName,
          value: el.sellerId,
        }
      })

      filterTable.value?.changeOptions(1, optionItems)
    },
    { immediate: true, deep: true }
  )
  watch(
    () => props.markedtList,
    (newVal) => {
      let optionItems = newVal.map((el: any) => {
        return {
          label: el.marketplaceName,
          value: el.marketplaceId,
        }
      })

      filterTable.value?.changeOptions(0, optionItems)
    },
    { immediate: true, deep: true }
  )
</script>

<style lang="less" scoped>
  .settlement-report-list {
    height: calc(100vh - @menuAndTabHeight);
  }
</style>
